#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include "HelperUtils.h"

void dieWithError(const char* errorMessage) {
    perror(errorMessage);
    exit(1);
}

// Reads input from stdin
//  *line holds the string input by user
//  *size holds size of the string
// Return value less than 0 indicates error.
// Algorithm credited to Richard Heathfield.
int getLongLine (char **line, size_t *size) {
    // Result would be less than 0 if error occured
    int result = 0;
    size_t  count = 0,
            newSize = 0;
    char nextChar = 0;
    char *newLine = NULL;   // Temporary pointer to check realloc()

    // Allocate initial size as GL_START_SIZE
    if (*line == NULL) {
        *line = malloc(GL_START_SIZE);
        if (*line == NULL)  result = -1;    // malloc() failed
        else                *size = GL_START_SIZE;  // Update current size
    }
    
    // Get next character
    while (result == 0 && (nextChar = fgetc(stdin)) != '\n') {
        // Update size and realloc if necessary
        if (count + 2 >= *size) {
            newSize = 3 * (count + *size) / 2;
            newLine = realloc(*line, newSize);
            if (newLine == NULL) {
                result = -3;    // realloc() failed
            } else {
                *line = newLine;
                newLine = NULL;
                *size = newSize;
            }
        }
        // Store character in line
        if (result == 0)    (*line)[count++] = nextChar;
    }

    // Reduce the result size
    if (result == 0) {
        newSize = strlen(*line) + 1;
        newLine = realloc(*line, newSize);
        if (newLine != NULL) {
            *line = newLine;
            *size = newSize;
        }
    }
    
    return result;
}

